﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;

namespace DynamicGeometry
{
    public abstract partial class FigureStyle : IFigureStyle
    {
        public string Name { get; set; }
        public event PropertyChangedEventHandler PropertyChanged;

        public Style GetWpfStyle(IFigure figure)
        {
            Style result = new Style(typeof(FrameworkElement));
            ApplyToWpfStyle(result, figure);
            return result;
        }

        protected virtual void ApplyToWpfStyle(Style existingStyle, IFigure figure)
        {
            if (figure != null)
            {
                if (!figure.Enabled)
                {
                    existingStyle.Setters.Add(new Setter(FrameworkElement.OpacityProperty, 0.2));
                }
            }
        }

        public virtual IFigureStyle Clone()
        {
            var result = (IFigureStyle)this.MemberwiseClone();
            result.Name = "";
            return result;
        }

        public abstract FrameworkElement GetSampleGlyph();

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        Drawing drawing;
        [Ignore]
        public Drawing Drawing
        {
            get
            {
                return drawing;
            }
            set
            {
                if (drawing == value)
                {
                    return;
                }
                if (drawing != null)
                {
                    throw new InvalidOperationException("A style can only be used by"
                        + " one drawing. This style is already assigned to a drawing"
                        + " and the code path in the call stack is trying to assign"
                        + " it to another Drawing.");
                }
                drawing = value;
            }
        }

        public virtual void OnApplied(IFigure figure, FrameworkElement element)
        {
            
        }

        public override string ToString()
        {
            var values = IncludeByDefaultValueDiscoveryStrategy.Instance
                    .GetValues(this)
                    .Select(v => v.WriteValue());
            var result = string.Join(" ", values.ToArray());
            return result;
        }
    }
}